package com;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PictureCheckCode extends HttpServlet {

	private static final long serialVersionUID = 5939150141630225893L;

	public PictureCheckCode() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void init() throws ServletException {
		super.init();
	}

	// 生成随机颜色的方法
	public Color getRandColor(int s, int e) {
		Random random = new Random();
		if (s > 255) {
			s = 255;
		}
		if (e > 255) {
			e = 255;
		}
		int r = s + random.nextInt(e - s);
		int g = s + random.nextInt(e - s);
		;
		int b = s + random.nextInt(e - s);
		;
		return new Color(r, g, b);
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 禁止缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setDateHeader("Expires", 0);
		// 指定生成的相应图片
		response.setContentType("image/jpeg");
		int width = 90;
		int height = 30;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Random random = new Random();
		Font mFont = new Font("微软雅黑", Font.BOLD, 16);
		g.setColor(getRandColor(200, 250));
		// 绘制填色巨型
		g.fillRect(0, 0, width, height);
		// 生成4个英文和数字混合的验证码
		g.setFont(mFont);
		String sRand = "";
		int itmp = 0;
		for (int i = 0; i < 4; i++) {
			if (random.nextInt(2) == 1) {
				itmp = random.nextInt(26) + 65; // A~Z
			} else {
				itmp = random.nextInt(10) + 48; // 0~9
			}
			char ctmp = (char) itmp;
			sRand += String.valueOf(ctmp);
			Color color = new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110));
			g.setColor(color);
			g.drawString(String.valueOf(ctmp), 20 * i + 1, 16);
		}
		HttpSession session = request.getSession();
		session.setAttribute("rcheckCode", sRand);
		// System.out.println(sRand);
		g.dispose();
		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

}
